﻿using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.VisualStudio.Services.Client;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace CMS6Tools.Common.TFS
{
    // we can still use the same WebAccessProxy for both 2013 and 2015
    public class Tfs2015WebAccessProxy : IWebAccessProxy
    {
        static readonly string UserNameWithDomain = ConfigurationManager.AppSettings["userNameWithDomain"];
        static readonly string Password = ConfigurationManager.AppSettings["password"];

        public Team GetTeamCapacitySettings(Project project, string teamName, bool isDefaultTeam, string iterationPath, string iterationID)
        {
            var teamProjectCollection = project.Store.TeamProjectCollection;

            //teamName = "CMS 6 Team";
            //var iterationPathUrl = iterationPath.Replace(project.Name + "\\", "");
            //iterationPathUrl = iterationPathUrl.Replace("\\", "/");
            //var requestUriString = string.Format("{0}/{1}/{2}/_apis/work/TeamSettings/Iterations/{3}/Capacities", teamProjectCollection.Uri, project.Name, teamName, iterationID);
             
            // We need to enable Basic Authentication mode in IIS.
            //var username = "NETVIP\\yuliang";
            //var password = "*******";
            //var responseBody = string.Empty;
            //using (HttpClient client = new HttpClient())
            //{
            //    client.DefaultRequestHeaders.Accept.Add(
            //        new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            //    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
            //        Convert.ToBase64String(
            //            System.Text.ASCIIEncoding.ASCII.GetBytes(
            //                string.Format("{0}:{1}", username, password))));

            //    using (HttpResponseMessage response = client.GetAsync(requestUriString).Result)
            //    {
            //        response.EnsureSuccessStatusCode();
            //        responseBody = response.Content.ReadAsStringAsync().Result; 
            //    }
            //}
            //dynamic capacityObject = JsonConvert.DeserializeObject(responseBody);

            var team = new Team()
            {
                ActivityValues = new string[] { },
                IsMultipleActivityPerMemberSupported = true,
                CurrentDate = DateTime.Now,
                TeamCapacity = new TeamCapacity
                {
                    TeamDaysOffDates = new DaysOffDates[]{},
                    TeamMemberCapacityCollection = new TeamMemberCapacity []{}
                }
            };

            var credentials = default(Microsoft.VisualStudio.Services.Common.VssCredentials);
            if (!string.IsNullOrEmpty(UserNameWithDomain))
            {
                var domain = string.Empty;
                var userName = UserNameWithDomain;
                var index = userName.IndexOf("\\");
                if (index > 0 && index < userName.Length - 1)
                {
                    domain = userName.Substring(0, index);
                    userName = userName.Substring(index + 1, userName.Length - index - 1);
                }

                var networkCredential = new NetworkCredential(userName, Password);
                if (!string.IsNullOrEmpty(domain))
                    networkCredential.Domain = domain;
                credentials = new Microsoft.VisualStudio.Services.Common.VssCredentials(new Microsoft.VisualStudio.Services.Common.WindowsCredential(networkCredential));
            }
            else
            {
                credentials = new Microsoft.VisualStudio.Services.Common.VssCredentials(true);
            }

            var connection = new VssConnection(teamProjectCollection.Uri, credentials);
            var workHttpClient = connection.GetClient<Microsoft.TeamFoundation.Work.WebApi.WorkHttpClient>();

            var teamContext= new Microsoft.TeamFoundation.Core.WebApi.Types.TeamContext(project.Name);
            var iterationGuid =  Guid.Parse(iterationID);
            
            var capacities = workHttpClient.GetCapacitiesAsync(teamContext,iterationGuid).Result;
            team.TeamCapacity.TeamMemberCapacityCollection = capacities.Select(a => new TeamMemberCapacity
            {
                Activities = a.Activities.Select(b => new TeamMemberActivity { CapacityPerDay = b.CapacityPerDay, Name = b.Name }).ToArray(),
                DaysOff = a.DaysOff.Select(b => new DaysOffDates { Start = b.Start, End = b.End }).ToArray(),
                TeamMember = new TeamMemberInfo
                {
                    DisplayName = a.TeamMember.DisplayName,
                    Id = a.TeamMember.Id,
                    ImageUrl = a.TeamMember.ImageUrl,
                    UniqueName = a.TeamMember.UniqueName,
                    Url = a.TeamMember.Url
                }
            }).ToArray();
            
            var iterationInfo = workHttpClient.GetTeamIterationAsync(teamContext, iterationGuid).Result;
            team.IterationStartDate = iterationInfo.Attributes.StartDate.Value;
            team.IterationEndDate = iterationInfo.Attributes.FinishDate.Value;

            //var daysOffInfo = workHttpClient.GetTeamDaysOffAsync(teamContext, iterationGuid).Result;

            //var teamFieldsValues = workHttpClient.GetTeamFieldValuesAsync(teamContext).Result;
            
            var teamSettings = workHttpClient.GetTeamSettingsAsync(teamContext).Result;
            team.Weekends = Enum.GetValues(typeof(DayOfWeek)).Cast<DayOfWeek>().Where(a => !teamSettings.WorkingDays.Contains(a)).Select(a => (int)a).ToArray();
             
            connection.Disconnect();

            team.ConvertMultipleActivityToSingle();

            return team;
        }
    }
}
